package com.xw.controller;

import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.xw.common.Constants;
import com.xw.common.Result;
import com.xw.common.TokenHandler;
import com.xw.dao.CommentDao;
import com.xw.entity.Comment;
import com.xw.entity.User;
import com.xw.req.PageRequest;
import com.xw.service.CommentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Date;

/**
 * @Description: 评论表控制器
 * @Author: 72478
 * @Date: 2024/12/18 16:53
 * @Version: 1.0
 */
@RestController
@RequestMapping("comment")
@Api(tags = "评论表")
public class CommentController {
    /**
    * 服务对象
    */
    @Resource
    private CommentService commentService;

    @Resource
    private CommentDao commentDao;

    /**
    * 分页查询
    * @return 查询结果
    */
    @PostMapping
    @ApiOperation(value = "分页查询")
    public Result<?> findPage(@RequestBody PageRequest<Comment> pageRequest) {
        return new Result<>(this.commentService.queryByPage(pageRequest),Constants.SUCCESS);
    }


    /**
    * 发表评论
    * @param comment 实体
    * @return 新增/修改结果
    */
    @PutMapping
    @ApiOperation(value = "发表评论")
    public Result<?> saveOrUpdate(@RequestBody @Validated Comment comment) {
        User userInfo = TokenHandler.getUserInfo();
        comment.setCommentUserId(userInfo.getId());
        comment.setCommentTime(new Date());
        comment.setCommentUserName(userInfo.getUserName());
        comment.setCommentUserPic(userInfo.getImageUrl());
        if (SensitiveWordHelper.contains(comment.getContent())) {
            // 如果包含敏感词，返回错误信息
            return new Result<>(Constants.ERROR, "帖子内容包含敏感词，无法发布");
        }else {
            this.commentDao.insert(comment);
            return new Result<>(Constants.SUCCESS);
        }
    }

    /**
    * 删除数据
    *
    * @param id 主键
    * @return 删除是否成功
    */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除数据(ID)")
    public Result<?> delete(@PathVariable("id") Integer id) {
        this.commentDao.deleteById(id);
        return new Result<>(Constants.SUCCESS);
    }

}